<?php

namespace Common\Model;

use Think\Model;

class NoticeModel extends Model
{
    public function update($data)
    {
        if (empty($data['id'])) {
            $result = $this->add($data);
        } else {
            $result = $this->save($data);
            $result = $data['id'];
        }
        return $result;
    }

    public function delete($id)
    {
        $data['status'] = -1;
        $result = $this->where('id=%d', $id)->save($data);
        if ($result) {
            return true;
        }
        return false;
    }

    public function get_list($search_key, $status, $page_no = 1, $page_size = 0, $attribute = 0, $rank = 0)
    {
        $condition = $this->assembleCondition($search_key, $status, $attribute, $rank);
        $count = 0;

        if ($page_size > 0) {
            $list = $this->where($condition)->order('id desc')->limit(($page_no - 1) * $page_size, $page_size)->select();
            $count = $this->where($condition)->count();
        } else {
            $list = $this->where($condition)->order('id desc')->select();
        }
        return [$list, $count];
    }

    private function assembleCondition($search_key, $status, $attribute, $rank)
    {
        $condition = array();

        if (!empty($search_key)) {
            $condition['title'] = array('like', '%' . $search_key . '%');
        }
        if (!empty($attribute)) {
            $condition['attribute'] = array('eq', $attribute);
        }
        if (!empty($rank)) {
            $condition['rank'] = array('eq', $rank);
        }
        if ($status != "" && $status != null) {
            $condition['status'] = array('eq', $status);
        } else {
            $condition['status'] = array('egt', 0);
        }

        return $condition;
    }
}